package com.eightbears.beboy.ui.user.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.ShopInfoAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.builder.GetBuilder;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.beboy.base.view.popupwindow.AutoSortPopup;
import com.eightbears.beboy.base.view.popupwindow.FindClassifyPopup;
import com.eightbears.beboy.base.view.popupwindow.LocationSortPopup;
import com.eightbears.beboy.entity.ClassifyEntity;
import com.eightbears.beboy.entity.LocationEntity;
import com.eightbears.beboy.entity.ShopListEntity;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.greendao.District;
import com.socks.library.KLog;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.cache.DistrictCache.CODE_DISTRICT;
import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.PARAMS_PAGE_SIZE;
import static com.eightbears.beboy.base.util.CommonAPI.URL_SHOPS_LIST;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.SearchShopActivity.PARAMS_SEARCH_KEY;
import static com.eightbears.beboy.ui.user.activity.SearchShopActivity.PARAMS_SEARCH_SHOP_TYPE;
import static com.eightbears.beboy.ui.user.fragment.FindFragment.PARAMS_SHOP_ID;

public class SearchShopResultActivity extends BaseActivity implements
        BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener,
        DistrictSearch.OnDistrictSearchListener {

    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.view_empty)
    View view_empty;
    @BindView(R.id.tv_classify)
    TextView tv_classify;
    @BindView(R.id.tv_location)
    TextView tv_location;
    @BindView(R.id.tv_result_sort)
    TextView tv_result_sort;
    @BindView(R.id.ll_find_top)
    LinearLayout ll_find_top;
    @BindView(R.id.ll_all)
    LinearLayout ll_all;
    @BindView(R.id.ll_rank)
    LinearLayout ll_rank;
    @BindView(R.id.ll_location)
    LinearLayout ll_location;
    @BindView(R.id.view_top)
    View view_top;

    private LocationEntity locationEntity;

    private String searchKey;
    private String classifyId;
    private String orderId;
    private String distanceId;
    private String districtId;
    private int page = 1;
    private boolean isErr = true;
    private int isEnd = 0;

    private ShopInfoAdapter shopInfoAdapter;
    private ShopListEntity.DataBean.ListBean shopEntity;
    private FindClassifyPopup findClassifyPopup;
    private AutoSortPopup autoSortPopup;
    private LocationSortPopup locationSortPopup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_shop_result);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        tv_title.setText(R.string.text_search_result);
        initAdapter();
        initPopup();
    }

    @Override
    protected void initData() {
        searchKey = getIntent().getStringExtra(PARAMS_SEARCH_KEY);
        classifyId = getIntent().getStringExtra(PARAMS_SEARCH_SHOP_TYPE);
        locationEntity = SPUtil.getUserLocation();
        if (!isNetWorkConnected(this))
            return;
        getShopInfo();
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
        shopInfoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.shop_info_root) {
                    shopEntity = (ShopListEntity.DataBean.ListBean) adapter.getData().get(position);
                    startLocalActivity(SearchShopResultActivity.this,
                            ShopDetailActivity.class, PARAMS_SHOP_ID, shopEntity.getShop_id());
                }
            }
        });
        initLeftEvent();
    }

    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        shopInfoAdapter = new ShopInfoAdapter();
        shopInfoAdapter.openLoadAnimation();
        shopInfoAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(shopInfoAdapter);
    }

    private void initPopup() {
        findClassifyPopup = new FindClassifyPopup(this);
        autoSortPopup = new AutoSortPopup(this);
        locationSortPopup = new LocationSortPopup(this);
    }

    private void initLeftEvent() {
        // 点击全部
        ll_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openFindClassify();
            }
        });

        ll_rank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openAutoSort();
            }
        });

        ll_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openLocationSort();
            }
        });
    }

    /**
     * 获取商铺信息
     */
    private void getShopInfo() {
        GetBuilder shopsBuilder = new GetBuilder();
        shopsBuilder.addHeader(KEY_HTTP_HEADER, "Bearer " + SPUtil.getAccessToken());
        shopsBuilder.url(URL_SHOPS_LIST);
        shopsBuilder.addParams("page", String.valueOf(page));
        shopsBuilder.addParams("size", PARAMS_PAGE_SIZE);
        shopsBuilder.addParams("user_lat", locationEntity.getLatitude());
        shopsBuilder.addParams("user_lng", locationEntity.getLongitude());
        shopsBuilder.addParams("order", "1");
        shopsBuilder.addParams("user_city_id", locationEntity.getCityId());
        if (!TextUtils.isEmpty(classifyId))
            shopsBuilder.addParams("type", classifyId);
        if (!TextUtils.isEmpty(searchKey))
            shopsBuilder.addParams("keyword", searchKey);
        if (!TextUtils.isEmpty(distanceId))
            shopsBuilder.addParams("distance", distanceId);
        if (!TextUtils.isEmpty(orderId))
            shopsBuilder.addParams("order", orderId);
        if (!TextUtils.isEmpty(districtId))
            shopsBuilder.addParams("district_id", districtId);
        shopsBuilder.build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                swipeLayout.setRefreshing(false);
                ShopListEntity shopListEntity = GsonUtil.fromJson(response, ShopListEntity.class);
                if (shopListEntity.getStatus_code().equals(CONNECTION_STATUS_SUCCESS)) {
                    if (CONNECTION_STATUS_SUCCESS.equals(shopListEntity.getStatus_code())) {
                        isEnd = shopListEntity.getData().isIs_end();
                        if (page == 1) {
                            shopInfoAdapter.setNewData(shopListEntity.getData().getList());
                            if (shopInfoAdapter.getData().size() == 0)
                                view_empty.setVisibility(View.VISIBLE);
                            else
                                view_empty.setVisibility(View.GONE);
                        } else {
                            shopInfoAdapter.addData(shopListEntity.getData().getList());
                            shopInfoAdapter.loadMoreComplete();
                        }
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                swipeLayout.setRefreshing(false);
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(SearchShopResultActivity.this, status_error);
            }
        });
    }


    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }


    /**
     * 按分类筛选
     */
    private void openFindClassify() {
        findClassifyPopup.setOnClickItemListener(new FindClassifyPopup.OnClickItemListener() {
            @Override
            public void onClickItem(ClassifyEntity classifyEntity) {
                tv_classify.setText(classifyEntity.getClassifyName());
                findClassifyPopup.selectItem(classifyEntity);
                classifyId = classifyEntity.getId();

                getSelShops();
            }
        });
        findClassifyPopup.showDropDown(view_top);
    }

    private void openAutoSort() {
        autoSortPopup.setOnClickItemListener(new AutoSortPopup.OnClickItemListener() {
            @Override
            public void onClickItem(ClassifyEntity classifyEntity) {
                tv_result_sort.setText(classifyEntity.getClassifyName());
                autoSortPopup.selectItem(classifyEntity);
                orderId = classifyEntity.getId();
                getSelShops();
            }
        });
        autoSortPopup.showDropDown(view_top);
    }

    private void openLocationSort() {

        // 左边菜单
        locationSortPopup.setOnMenuClickListener(new LocationSortPopup.OnMenuClickListener() {
            @Override
            public void onMenuClick(ClassifyEntity menuEntity) {
                tv_location.setText(menuEntity.getClassifyName());
                locationSortPopup.selectMenu(menuEntity);
            }
        });


        // 选择距离
        locationSortPopup.setOnClickItemListener(new LocationSortPopup.OnClickItemListener() {
            @Override
            public void onClickItem(ClassifyEntity classifyEntity) {
                locationSortPopup.selectItem(classifyEntity);
                distanceId = classifyEntity.getId();
                locationSortPopup.selectDistrict(null);
                districtId = "";
                getSelShops();
            }
        });

        // 选择区域
        locationSortPopup.setOnDistrictClickListener(new LocationSortPopup.OnDistrictClickListener() {
            @Override
            public void onDistrictClick(District district) {
                locationSortPopup.selectDistrict(district);
                tv_location.setText(district.getName());
                locationSortPopup.selectItem(null);

                DistrictSearch search = new DistrictSearch(SearchShopResultActivity.this);
                DistrictSearchQuery query = new DistrictSearchQuery();
                query.setKeywords(district.getName());//传入关键字
                query.setShowBoundary(true);//是否返回边界值
                search.setQuery(query);
                search.setOnDistrictSearchListener(SearchShopResultActivity.this);
                search.searchDistrictAnsy();//开始搜索
            }
        });

        locationSortPopup.showDropDown(view_top);
    }

    private void getSelShops(){
        isErr = true;
        page = 1;
        shopInfoAdapter.getData().clear();
        getShopInfo();
        shopInfoAdapter.setEnableLoadMore(true);
    }

    @Override
    public void onRefresh() {
        shopInfoAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isNetWorkConnected(SearchShopResultActivity.this)) {
                    swipeLayout.setRefreshing(false);
                    return;
                }
                isErr = true;
                page = 1;
                shopInfoAdapter.getData().clear();
                getShopInfo();
                shopInfoAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    shopInfoAdapter.loadMoreEnd(true);
                } else {
                    if (isErr) {
                        page++;
                        getShopInfo();
                    } else {
                        isErr = true;
                        ShowToast.showShortToast(R.string.network_anomalies);
                        shopInfoAdapter.loadMoreFail();
                    }
                }
            }
        }, delayMillis);
    }

    @Override
    public void onDistrictSearched(DistrictResult districtResult) {
        if (null != districtResult.getDistrict() && districtResult.getDistrict().size() > 0) {
            String disName = districtResult.getDistrict().get(0).getName();
            District district = DistrictCache.getInstance(SearchShopResultActivity.this)
                    .getCacheByName(disName, CODE_DISTRICT, locationEntity.getCityId());
            districtId = district.getId();
            distanceId = "0";
            getShopInfo();
        }
    }
}
